package com.xxmw.transaction.service.support;

import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.xxmw.transaction.model.app.BoursePrice;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
public abstract class AbstractWebSocketAdapter implements InitializingBean, DisposableBean {

	protected static final Sequence sequence = new Sequence();

	public static final String PING = "ping";

	public static final String PONG = "pong";

	protected final ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();

	protected final HashMap<String, BoursePrice> symbol_map = new HashMap<>(16);

	private Boolean isConnect = true;

	/**
	 * WebSocket
	 */
	protected WebSocketClient client;

	protected AbstractWebSocketAdapter() {}

	public void afterPropertiesSet(Object client) {
		this.client = (WebSocketClient)client;
	}

	public void heartBeat() {
		if(isConnect) {
            log.info("webSocket启动");
			this.client.connect();
            this.isConnect = false;
		}else if(!this.client.isOpen()) {
            log.info("webSocket重连");
			this.client.reconnect();
		}else {
			/*log.info("未知状态,重新连接");
			this.client.reconnect();*/
		}
	}
}
